/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.ai.biz.controller;

import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.ClassPathDocumentLoader;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.apache.tika.ApacheTikaDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentByLineSplitter;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.ollama.OllamaStreamingChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import jakarta.servlet.http.HttpServletResponse;

import java.net.URL;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.annotations.security.IgnoringAuthentication;
import org.elsfs.cloud.module.ai.api.service.AiEmbeddingStoreService;
import org.elsfs.cloud.module.ai.biz.service.Assistant;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * ai 聊天
 *
 * @author zeng
 */
@Slf4j
@RequestMapping("/ai")
@RequiredArgsConstructor
@RestController
public class AiChatController {

  private final AiEmbeddingStoreService aiEmbeddingStoreService;

  /**
   * 聊天
   *
   * @param userMessage 聊天
   * @return 聊天
   */
  @GetMapping("/chat")
  @IgnoringAuthentication
  public String chat(@RequestParam(value = "msg",defaultValue = "怎么新建一个模块，模块是order，名称是订单") String userMessage) {

      List<Document> documents = FileSystemDocumentLoader
              .loadDocuments(getClass().getClassLoader().getResource("rag").getPath(), new ApacheTikaDocumentParser());
      var embeddingStore = aiEmbeddingStoreService.getEmbeddingStoreByStoreId("1935344286862430209");
      // 默认我们选择bge-small-en-v1.5作为 Easy RAG 的默认嵌入模型
      EmbeddingStoreIngestor
              .builder()
              // LangChain4j 具有DocumentSplitter多个开箱即用的实现接口：
              // DocumentByParagraphSplitter  按段落拆分文档
              .documentSplitter(new DocumentByLineSplitter(48, 20))
              .embeddingStore(embeddingStore)
              .build()
              .ingest(documents);
      OpenAiChatModel chatModel= OpenAiChatModel.builder()
                .modelName("deepseek-chat")
                .apiKey(System.getenv("DEEPSEEK_KEY"))
                .baseUrl("https://api.deepseek.com")
                .build();
      Assistant assistant = AiServices.builder(Assistant.class)
              .chatModel(chatModel)
              .systemMessageProvider(chatMemoryId -> "你是一名专业程序员，回答的时候需要更精确") // 系统提示词
              .chatMemory(MessageWindowChatMemory.withMaxMessages(10))
              .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
              .build();
      return assistant.chat(userMessage);
  }

//  /**
//   * 流式返回
//   *
//   * @param request request
//   * @param response response
//   * @return s
//   */
//  @PostMapping(
//      value = "/stream",
//      produces = MediaType.TEXT_EVENT_STREAM_VALUE,
//      consumes = MediaType.APPLICATION_JSON_VALUE)
//  public Flux<String> streamChat(
//      @RequestBody StreamChatRequest request, HttpServletResponse response) {
//
//    response.setCharacterEncoding("UTF-8");
//
//    UserMessage userMessage = UserMessage.from(request.message());
//
//    List<ChatMessage> messages = List.of(userMessage);
//
//    OllamaStreamingChatModel chatModel =
//        OllamaStreamingChatModel.builder().modelName("deepseek-r1:1.5b").build();
//
//    return Flux.create(
//        sink -> {
//          chatModel.chat(
//              messages,
//              new StreamingChatResponseHandler() {
//                @Override
//                public void onPartialResponse(String partialResponse) {
//                  sink.next(partialResponse);
//                  // data:需要帮助，欢迎
//                  //
//                  // data:随时向我提问！
//                }
//
//                @Override
//                public void onCompleteResponse(ChatResponse completeResponse) {
//                  //                    log.info("complete:{}", completeResponse);
//                  sink.next("[DONE]");
//                  sink.complete();
//                }
//
//                @Override
//                public void onError(Throwable error) {
//                  sink.error(error);
//                }
//              });
//        });
//  }
//
//  /**
//   * 请求
//   *
//   * @param userId userId
//   * @param message message
//   */
//  public record StreamChatRequest(String userId, String message) {}
}
